<template>
  <div class="card-container">
    <!-- 新增删除操作区域 -->
    <div class="create-container">
      <el-button type="primary" @click="addBuilding">添加区域</el-button>
      <!-- 添加楼宇弹框 -->
      <el-dialog
        :title="id ? '编辑区域' : '添加区域'"
        :visible="dialogVisible"
        width="580px"
        @close="closeDialog"
      >
        <!-- 表单接口 -->
        <div class="form-container">
          <el-form ref="buildForm" :model="addForm" :rules="addFormRules">
            <el-form-item label="区域名称" prop="areaName">
              <el-input v-model="addForm.areaName" />
            </el-form-item>
            <el-form-item label="车位数（个）" prop="areaProportion">
              <el-input v-model="addForm.areaProportion" />
            </el-form-item>
            <el-form-item label="面积（㎡）" prop="spaceNumber">
              <el-input v-model="addForm.spaceNumber" />
            </el-form-item>
            <el-form-item label="关联计费规则" prop="ruleId">
              <el-select v-model="addForm.ruleId" clearable>
                <el-option
                  v-for="item in AreaDropList"
                  :key="item.ruleId"
                  :value="item.ruleId"
                  :label="item.ruleName"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="备注" prop="remark">
              <el-input v-model="addForm.remark" type="textarea" />
            </el-form-item>
          </el-form>
        </div>
        <template #footer>
          <el-button size="mini" @click="closeDialog">取 消</el-button>
          <el-button size="mini" type="primary" @click="addNewBuilding">确 定</el-button>
        </template>
      </el-dialog>
    </div>
    <!-- 表格区域 -->
    <div class="table">
      <el-table style="width: 100%" :data="tableData">
        <el-table-column type="index" label="序号" />
        <el-table-column label="区域名称" prop="areaName" />
        <el-table-column label="车位数（个）" prop="areaProportion" />
        <el-table-column label="面积（㎡）" prop="spaceNumber" />
        <el-table-column label="计费规则" prop="ruleName" />
        <el-table-column label="备注" prop="remark" />
        <el-table-column label="操作" fixed="right" width="180">
          <template #default="scoup">
            <el-button size="mini" type="text" @click="edit(scoup.row)">编辑</el-button>
            <el-button size="mini" type="text" @click="del(scoup.row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- 分页 -->
    <div class="page-container">
      <el-pagination
        layout="total, prev, pager, next , sizes"
        :total="total"
        :current-page.sync="currentpage"
        :page-sizes="[10,20,50,100]"
        :page-size="query.pageSize"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
  </div>
</template>

<script>
// 目标：分页组件数据联动效果
// 思路：
// 1.准备标签（条/页）下拉菜单准备好
// 2.共多少页数据准备显示好
// 3.准备显示下拉菜单（ 2 4 6 8 10 ）范围
// 4.实现2条 一页
// 5.解决页码个数不对的问题
// 6.（功能）切换页码切换数据功能
// 7.每页条数的功能切换
// 复用经验：页码切换都围绕着 query 参数修改对应属性值，再让请求重新发起

// 经验：如果你知道列表所有可能的情况的值
// 那么就可以在前端实现枚举列表数据(或者后端给发)

import { getAreaAPI, getAreaDropListAPI, addAreaAPI, delAreaAPI, updateAreaAPI } from '@/apis/car'
export default {
  data() {
    return {
      query: {
        // 唯一查询参数对象（分页参数2个）
        page: 1,
        pageSize: 10
      },
      tableData: [], // 列表数据
      AreaDropList: [], // 区域下拉菜单数据
      total: 0, // 总条数
      currentpage: 1, // 当前页
      ids: '',
      dialogVisible: false,
      id: '',
      addForm: {
        areaName: '',
        areaProportion: '',
        spaceNumber: '',
        ruleId: '',
        remark: ''
      },
      addFormRules: {
        areaName: [
          { required: true, message: '请输入区域名称', trigger: 'blur' }
        ],
        areaProportion: [
          { required: true, message: '请输入车位数（单位个）', trigger: 'blur' }
        ],
        spaceNumber: [
          { required: true, message: '请输入区域面积', trigger: 'blur' }
        ],
        ruleId: [
          { required: true, message: '请关联计费规则', trigger: 'blur' }
        ]
      },
      statusList: [
        {
          value: '', // 代码和后台要用的对应标记
          label: '全部' // 显示给用户的
        },
        {
          value: '0',
          label: '可用'
        },
        {
          value: '1',
          label: '已过期'
        }
      ]
    }
  },
  created() {
    this.getAreaList()
    this.getAreaDropList()
  },
  methods: {
    // 获取区域列表
    async getAreaList() {
      const res = await getAreaAPI(this.query)
      this.tableData = res.data.rows
      this.total = res.data.total
    },
    // 获取下拉列表
    async getAreaDropList() {
      const res = await getAreaDropListAPI()
      this.AreaDropList = res.data
      console.log(this.AreaDropList)
    },
    // 格式化表格内容
    formatterFn(row) {
      // return row.cardStatus === 0 ? '可用' : '已过期'
      // 字典对象
      const keyObj = {
        0: '可用',
        1: '已过期'
      }
      return keyObj[row.cardStatus]
    },
    // 分页下拉列表
    handleSizeChange(val) {
      this.query.pageSize = val
      this.currentpage = 1
      this.handleCurrentChange()
    },
    handleCurrentChange(val) {
      this.query.page = val
      this.getAreaList()
    },
    // 查询按钮点击
    searchFn() {
      // 问题：你在第二页查询只有一条符合条件
      // 解决方案：回到第一页
      this.query.page = 1
      this.getAreaList()
    },
    edit(row) {
      console.log(row)
      const { areaName, areaProportion, spaceNumber, ruleId, remark
      } = row
      this.addForm = {
        areaName, areaProportion, spaceNumber, ruleId, remark
      }
      this.id = row.id
      this.addBuilding()
    },
    async del(id) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        await delAreaAPI(id)
        this.$message.success('删除成功')
        this.query.page = 1
        this.getAreaList()
      })
    },
    // 表格选择框的选项发生变化时
    handleSelectionChange(val) {
      // val：是选中的这些行的数据对象的数组集合
      this.ids = val.map(item => item.id).join(',')
    },
    // 打开弹窗
    addBuilding() {
      this.dialogVisible = true
    },
    // 关闭弹窗
    closeDialog() {
      this.$refs.buildForm.resetFields()
      this.addForm = {}
      this.id = ''
      this.dialogVisible = false
    },
    // 添加功能 和编辑功能
    async addNewBuilding() {
      if (this.id) {
        // 编辑功能
        this.$refs.buildForm.validate()
        const obj = { id: this.id, ...this.addForm }
        console.log(obj)
        const res = await updateAreaAPI(obj)
        console.log(res)
        this.id = ''
      } else {
        // 新增功能
        this.$refs.buildForm.validate()
        await addAreaAPI(this.addForm)
      }
      this.query.page = 1
      this.getAreaList()
      this.$refs.buildForm.resetFields()
      this.addForm = {}
      this.dialogVisible = false
    }
  }
}
</script>

<style lang="scss" scoped>
.card-container {
  padding: 20px;
  background-color: #fff;
}

.search-container {
  display: flex;
  align-items: center;
  border-bottom: 1px solid rgb(237, 237, 237, .9);
  padding-bottom: 20px;

  .search-main {
    width: 220px;
    margin-right: 10px;
  }

  .search-btn {
    margin-left: 20px;
  }
}

.create-container {
  margin: 10px 0px;
}

.page-container {
  padding: 4px 0px;
  text-align: right;
}

.form-container {
  padding: 0px 80px;
}
</style>
